package com.gexiaobao.pigeon.ui.pigeoncatcher

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.PolylineOptions
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.BusRouteResult
import com.amap.api.services.route.DriveRouteResult
import com.amap.api.services.route.RideRouteResult
import com.amap.api.services.route.RouteSearch
import com.amap.api.services.route.WalkRouteResult
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.util.AMapUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityOrderRoutePlanningBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.viewmodel.PigeonCatcherViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat


/**
 * @Author      : hxw
 * @Date        : 2024/7/1 13:21
 * @Describe    : 接单详情（路线规划）
 */
class ActivityOrderRoutePlanning : BaseActivity<PigeonCatcherViewModel, ActivityOrderRoutePlanningBinding>(), RouteSearch.OnRouteSearchListener {

    private var mLatitude: Double = 0.0
    private var mLongitude: Double = 0.0
    private var driverLat: Double = 0.0
    private var driverLng: Double = 0.0
    private var destinationName = ""
    private var phone = ""
    private var name = ""

    private lateinit var aMap: AMap
    private var startMarker: MarkerOptions? = null
    private var endMarker: MarkerOptions? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mDatabind.mapView.onCreate(savedInstanceState)
    }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mLatitude = intent.getDoubleExtra("lat", 0.0)
        mLongitude = intent.getDoubleExtra("lon", 0.0)
        driverLat = intent.getDoubleExtra("driverLat", 0.0)
        driverLng = intent.getDoubleExtra("driverLng", 0.0)
        destinationName = intent.getStringExtra("address").toString()
        phone = intent.getStringExtra("phone").toString()
        name = intent.getStringExtra("name").toString()
        mDatabind.tvRoutePlanningName.text = "鸽主: $name"
        if (phone.isNotEmpty() && phone.length >= 11) {
            val result1 = phone.substring(0, 3)
            val result2 = phone.substring(7, phone.length)
            mDatabind.tvRoutePlanningPhone.text = "电话: $result1****$result2"
        }
        initMap()
        searchRoute()
    }

    private fun searchRoute() {
        val routeSearch = RouteSearch(this)
        routeSearch.setRouteSearchListener(this)

        aMap.addMarker(startMarker)
        aMap.addMarker(endMarker)

        val start: LatLng? = AMapUtil.BD2GCJ(LatLng(driverLat, driverLng)) //坐标转换
        val end: LatLng? = AMapUtil.BD2GCJ(LatLng(mLatitude, mLongitude))

        val fromLatLon = LatLonPoint(start!!.latitude, start.longitude) // 起点经纬度
        val toLatLon = LatLonPoint(end!!.latitude, end.longitude) // 终点经纬度

        // 添加起点和终点标记
        startMarker = MarkerOptions()
            .position(LatLng(fromLatLon.latitude, fromLatLon.longitude))
            .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(resources, R.mipmap.icon_start_marker)))
            .title("起点")

        endMarker = MarkerOptions()
            .position(LatLng(toLatLon.latitude, toLatLon.longitude))
            .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(resources, R.mipmap.icon_end_marker)))
            .title("终点")

        aMap.addMarker(startMarker)
        aMap.addMarker(endMarker)

        val fromAndTo = RouteSearch.FromAndTo(fromLatLon, toLatLon)
        val query = RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DRIVING_SINGLE_DEFAULT, null, null, "")
        routeSearch.calculateDriveRouteAsyn(query)
    }

    private fun initMap() {
        aMap = mDatabind.mapView.map
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15f))
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivBack, mDatabind.btnMapNavigation, mDatabind.tvRoutePlanningCall) {
            when (it) {
                mDatabind.ivBack -> {
                    finish()
                }

                mDatabind.tvRoutePlanningCall -> {
                    showCallDialog()
                }

                mDatabind.btnMapNavigation -> {
                    showBottomMapDialog()
                }
            }
        }
    }

    @SuppressLint("MissingInflatedId")
    private fun showBottomMapDialog() {
        val bottomDialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val dialogView: View = LayoutInflater.from(this).inflate(R.layout.bottom_map_navigation, null)
        val tvMapGD = dialogView.findViewById<AppCompatTextView>(R.id.tvMapGDMap)
        val tvMapBD = dialogView.findViewById<AppCompatTextView>(R.id.tvMapBDMap)
        val tvMapTX = dialogView.findViewById<AppCompatTextView>(R.id.tvMapTXMap)
        val tvCancel = dialogView.findViewById<AppCompatTextView>(R.id.tvMapDialogCancel)

        tvMapGD.setOnClickListener {
            goToGaodeMap()
            bottomDialog.dismiss()
        }
        tvMapBD.setOnClickListener {
            goToBaiduMap()
            bottomDialog.dismiss()
        }
        tvMapTX.setOnClickListener {
            goToTencentMap()
            bottomDialog.dismiss()
        }
        tvCancel.setOnClickListener {
            bottomDialog.dismiss()
        }

        bottomDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        bottomDialog.setContentView(dialogView)
        bottomDialog.show()
    }

    private fun showCallDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setTitle("确定向以下手机号拨打电话？")
        dialog.setContent(mDatabind.tvRoutePlanningPhone.text.toString())
        dialog.setSureListener {
            requestPermission()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun requestPermission() {
        XXPermissions.with(this)
            .permission(Permission.CALL_PHONE)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(Intent.ACTION_CALL)
                    val data = Uri.parse("tel:$phone")
                    intent.setData(data)
                    startActivity(intent)
                } else {
                    RxToast.showToast("权限不足，请手动开启权限后重试")
                }
            }
    }

    /**
     * 跳转百度地图
     */
    private fun goToBaiduMap() {
        if (!AMapUtil.isInstalled("com.baidu.BaiduMap", this)) {
            RxToast.warning("请先安装百度地图客户端")
            return
        }
        val latLon = AMapUtil.BD2GCJ(LatLng(mLatitude, mLongitude))
        val intent = Intent()
        intent.setData(
            Uri.parse(
                (("baidumap://map/direction?destination=latlng:"
                        + latLon!!.latitude) + ","
                        + latLon.longitude) + "|name:" + destinationName +  // 终点
                        "&mode=driving" +  // 导航路线方式
                        "&src=" + packageName
            )
        )
        startActivity(intent) // 启动调用
    }


    /**
     * 跳转腾讯地图
     */
    private fun goToTencentMap() {
        if (!AMapUtil.isInstalled("com.tencent.map", this)) {
            RxToast.warning("请先安装腾讯地图客户端")
            return
        }
        val endPoint: LatLng? = AMapUtil.BD2GCJ(LatLng(mLatitude, mLongitude)) //坐标转换
        val stringBuffer = StringBuffer("qqmap://map/routeplan?type=drive")
            .append("&tocoord=").append(endPoint!!.latitude).append(",").append(endPoint.longitude).append("&to=$destinationName")
        val intent = Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()))
        startActivity(intent)
    }


    /**
     * 跳转高德地图
     */
    private fun goToGaodeMap() {
        if (!AMapUtil.isInstalled("com.autonavi.minimap", this)) {
            RxToast.warning("请先安装高德地图客户端")
            return
        }
        val endPoint: LatLng? = AMapUtil.BD2GCJ(LatLng(mLatitude, mLongitude)) //坐标转换
        val stringBuffer = StringBuffer("androidamap://navi?sourceApplication=").append("amap")
        stringBuffer.append("&lat=").append(endPoint!!.latitude)
            .append("&lon=").append(endPoint.longitude).append("&keywords=$destinationName")
            .append("&dev=").append(0)
            .append("&style=").append(2)
        val intent = Intent("android.intent.action.VIEW", Uri.parse(stringBuffer.toString()))
        intent.setPackage("com.autonavi.minimap")
        startActivity(intent)

    }

    override fun onBusRouteSearched(p0: BusRouteResult?, p1: Int) {}

    override fun onDriveRouteSearched(result: DriveRouteResult?, errorCode: Int) {
        if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.paths != null && result.paths.size > 0) {
                val drivePath = result.paths[0]
                val latLngList = mutableListOf<LatLng>()
                for (step in drivePath.steps) {
                    for (latLng in step.polyline) {
                        latLngList.add(LatLng(latLng.latitude, latLng.longitude))
                    }
                }
                val options = PolylineOptions()
                    .addAll(latLngList)
                    .width(10f)
                    .color(Color.BLUE)
                aMap.addPolyline(options)

                // 自动缩放地图，使整条路径都可见
                val boundsBuilder = LatLngBounds.Builder()
                for (latLng in latLngList) {
                    boundsBuilder.include(latLng)
                }
                val bounds = boundsBuilder.build()
                val padding = 100 // 地图缩放边界留白
                val cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding)
                aMap.moveCamera(cameraUpdate)
            } else {
                RxToast.warning("未查询到路径")
            }
        } else {
            RxToast.warning("路径规划失败")
        }
    }

    override fun onWalkRouteSearched(p0: WalkRouteResult?, p1: Int) {}

    override fun onRideRouteSearched(p0: RideRouteResult?, p1: Int) {}

    override fun onDestroy() {
        super.onDestroy()
        mDatabind.mapView.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        mDatabind.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mDatabind.mapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mDatabind.mapView.onSaveInstanceState(outState)
    }
}